package de.hsma.srn.model.key;

import java.security.Key;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;

import de.hsma.srn.model.user.UserModel;

/**
 * The Master Key Package extends the key package and specializes
 * it with an list of users, the file with the given file path is shared with.
 * So the master key package should be normally used by the owner of the file.
 * @author Axel Wilbertz & Tobias Hegemann
 *
 */
public class MasterKeyPackageModel extends KeyPackageModel {
	/*
	 * Members
	 */
	/**
	 * The list of the users the file with the given mFilePath is shared with
	 */
	private List<UserModel> mSharedUsers;

	
	/*
	 * Getter & Setter
	 */
	/**
	 * Returns the list of shared Users.
	 * The returned list is a reference, so you're able to modify it!
	 * @return the list of all shared Users
	 */
	public List<UserModel> getSharedUsers() {
		return mSharedUsers;
	}
	public void setSharedUsers(List<UserModel> users) {
		this.mSharedUsers = users;
	}
	/**
	 * Returns the decrypted symmetric key if given key is valid
	 * @param key to decrypt the symmetric key
	 * @return decrypted symmetric key if key was valid, null if not
	 */
	public Key getSymKey(Key key) {
		if(key==null) {
			return null;
		}
		// First decrypt the mEncSymmKey with the given Key (e.g. private key)
		Cipher cipher;
		Key fileKey;
		try {
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.UNWRAP_MODE, key);
            fileKey = (SecretKey) cipher.unwrap(this.mEncrSymKey, "AES", Cipher.SECRET_KEY);
		} catch (Exception e) {
			throw new RuntimeException("Spurious decryption error", e);
		}
		return fileKey;
	}
	
	
	/*
	 * Constructors
	 */
	/**
	 * Creates a new Master key package with the given filePath and (already) encrypted symmetric key.
	 * A list of the shared Users can also be appended or be null
	 * @param filePath the path to the encrypted file
	 * @param encrySymKey the already encrypted symmetric key
	 * @param sharedUsers list or null
	 */
	public MasterKeyPackageModel(String filePath, byte[] encrySymKey,
			List<UserModel> sharedUsers) {
		super(filePath, encrySymKey);
		if(sharedUsers==null) {
			this.mSharedUsers = new ArrayList<UserModel>();
		} else {
			mSharedUsers = sharedUsers;
		}
	}
}
